package com.client.task;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;

import com.client.bean.BirdMessage;
import com.client.bean.User;
import com.client.common.ValueStack;
import com.client.db.DataService;
import com.client.net.FormFile;
import com.client.net.Request;
import com.clinet.cache.Log;

public class AddBirdMessagesTask extends AsyncTask<BirdMessage, Void, Integer> {
	public interface Callback {

		void onComplete(final Integer result,int position);
	}

//	private int currPosition=-1;
	private final Context context;
	private Callback callback;
	private String addpath = ValueStack.ROOT
			+ "/forestry/birdMessage_add.action";
	
//	private DataService mDataService = null;
	private Request mRequest = null;

	private DataService  mDataService=null;
	public AddBirdMessagesTask(Context context, Callback callback,DataService dataService ) {
		this.context = context;
		this.callback = callback;
//		currPosition=postion;
		mDataService=dataService;
//			mDataService = new DataService(context);
	}

	// 正确返回：
	// {"items":[{"birdId":"40289381368be15b01368c0804e20002",
	// "birdImage":"753726d6cdc444cd96ef4d0fd1c18d73.jpg","birdName":"fdasg",
	// "collectLoaction":"","date":"","deadDes":"fdsgfdsg",
	// "deadImage":"381ba853e1dc4114a3b9e19cf3ac7891.jpg","deadNum":0,"direct":"","distance":"","healthNum":0,
	// "kind":"23","latitude":"","longitude":"","num":232,"place":"","sickDes":"43",
	// "sickImage":"81c7484b13664748b5fad4fa60c6b23e.jpg","sickNum":0,"status":"","stayPlace":""}],
	// "message":"OK","success":true,"totalNum":1}
	// 错误返回：
	// {"success":false,"message":"请输入用户名或密码!"}//没用登录的情况

	private List<FormFile> files=new ArrayList<FormFile>(); 
	/**
	 * The task should be executed with one given source photo uri.
	 */
//	private BirdMessage mBirdMessage=null;
	@Override
	protected Integer doInBackground(BirdMessage... params) {
		int code = 0;
		if (params[0] == null) {
			code = 0;
		} else {
			if (!iscancle) {
				isrunning=true;
				User muser = (User) ValueStack.getInstance().getSessionValue(
							"USER");
					Map<String, String> ps = new HashMap<String, String>();
					ps.put("username", muser.userName);
					ps.put("password", muser.password);
					mRequest = new Request(addpath);
					ps.put("birdId", params[0].birdId);
					ps.put("birdName",params[0].birdName);
					ps.put("distance", params[0].distance);
					ps.put("date", params[0].date);
					ps.put("sickDes", params[0].sickDes);
					ps.put("num", params[0].num);
					ps.put("kind", params[0].kind);
					ps.put("healthNum", params[0].healthNum);
					ps.put("sickNum", params[0].sickNum);
					ps.put("deadNum", params[0].deadNum);
					ps.put("deadDes", params[0].deadDes);
					ps.put("collectLoaction", params[0].collectLoaction);
					ps.put("place", params[0].place);
					ps.put("direct", params[0].direct);
					ps.put("stayPlace", params[0].stayPlace);
					ps.put("longitude", params[0].longitude);
					ps.put("latitude", params[0].latitude);
					ps.put("status", params[0].status);
					ps.put("uploaded", params[0].uploaded);
//					String path2 = Environment.getExternalStorageDirectory() + "/t.jpg";
					files.clear();
					
					if(!"".equals(params[0].birdImage))
					{
						File imageFile = new File(params[0].birdImage);
						FormFile birdImageFormFile = new FormFile(imageFile.getName(), imageFile,
								"birdImage", "image/jpg");
						files.add(birdImageFormFile);
					}
					
					if(!"".equals(params[0].sickImage))
					{
						File imageFile = new File(params[0].sickImage);
						FormFile sickImage = new FormFile(imageFile.getName(), imageFile,
								"sickImage", "image/jpg");
						files.add(sickImage);
					}
					if(!"".equals(params[0].deadImage))
					{
						File imageFile = new File(params[0].deadImage);
						FormFile deadImage = new FormFile(imageFile.getName(), imageFile,
								"deadImage", "image/jpg");
						files.add(deadImage);
					}
					String temp="";
					if(files.size()>0)
					{
						FormFile[] forms=	new FormFile[files.size()];
					    try {
					    	files.toArray(forms);
							temp = mRequest.postMultiFile(ps,forms);
						} catch (Exception e) {
							Log.i("Exception"+e.getMessage());
						}
					}else
					{
						 try {
							temp = mRequest.postFormData(ps);
						} catch (Exception e) {
							Log.i("Exception"+e.getMessage());
						}
					}
					addpath = addpath + ";jsessionid" + muser.sessionid;
					try {
						Log.i("postText" + temp);
						//{"success":true,"id":"40289381368cbe2301368cbf04e00001"}
						JSONObject obj = new JSONObject(temp);
						boolean falg = obj.getBoolean("success");
						if (falg) {
							code = 1;
							String id = obj.getString("id");
							params[0].birdId=id;
							params[0].uploaded="true";
							if(mDataService.hasBIRDMESSAGE(params[0]))
							{
								mDataService.updateBirdMessage(params[0]);
							}else
							{
								mDataService.saveBirdMessage(params[0]);
							}
							
						} else {
							code = 0;
						}
					} catch (Exception e) {
						Log.i("Exception"+e.getMessage());
					}
				} else {
					code = 1;
				}
		}
		return code;
	}
	@Override
	protected void onPostExecute(Integer result) {
		if (!iscancle && callback != null) {
			isrunning=false;
			callback.onComplete(result,result);
		}

	}
	

	private boolean isrunning=false;
	
	public boolean isIsrunning() {
		return isrunning;
	}

	public void setIsrunning(boolean isrunning) {
		this.isrunning = isrunning;
	}

	private boolean iscancle = false;
	public void release() {
		callback = null;
		iscancle=true;
	}
}
